/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.util;

import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @author
 * @apiNote 基础工具类
 * @date 2022/4/27 9:33
 */
public class CommTool {

	/**
     * 字符串转换成十六进制
     */
    public static String asciiToHex(String asciiStr) {
        char[] chars = asciiStr.toCharArray();

        StringBuilder hex = new StringBuilder();

        for (char ch : chars) {
            hex.append(Integer.toHexString((int) ch));

        }

        return hex.toString();

    }
    
    /**
     * 字节转换成十六进制
     */
    public static void printHexString(byte[] bytes) {
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase() + " ");
        }
    }

    /**
     * 字节数组装换成十六进制字符串（带空格）
     */
    public static String getHexString(byte[] bytes) {
        String str = "";
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            str += hex.toUpperCase() + " ";
        }
        return str.trim();
    }

    /**
     * 字节数组装换成十六进制字符串
     */
    public static StringBuilder getHexStringNoSpace(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            stringBuilder.append(hex.toUpperCase());
        }
        return stringBuilder;
    }

    /**
     * 数字十六进制字符串转换成整型
     */
    public static int hexadecimal16Conversion(String hexadecimalStr) {
        //转化得到的目标数据
        int getDataDecimal = 0;
        //16进制代表数据 4位数字
        if (hexadecimalStr.length() == 4) {
            //获取第一位。判断是正数还是负数
            int bit1Num = Integer.parseInt(hexadecimalStr.substring(0, 1), 16);
            //小于8是正数
            if (bit1Num < 8) {
                getDataDecimal = Integer.parseInt(hexadecimalStr, 16);
            } else { //负数
                //先补全八位
                hexadecimalStr = "FFFF" + hexadecimalStr;
//                System.out.println(hexadecimalStr);
                getDataDecimal = new BigInteger(hexadecimalStr, 16).intValue();
            }
            return getDataDecimal;
        }
        return 0;
    }

    /**
     * 十六进制字符串转换成字节数组
     */
    public static byte[] parseHexBinary(String s) {
        final int len = s.length();

        // "111" is not a valid hex encoding.
        if (len % 2 != 0)
            throw new IllegalArgumentException("hexBinary needs to be even-length: " + s);

        byte[] out = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            int h = hexToBin(s.charAt(i));
            int l = hexToBin(s.charAt(i + 1));
            if (h == -1 || l == -1)
                throw new IllegalArgumentException("contains illegal character for hexBinary: " + s);

            out[i / 2] = (byte) (h * 16 + l);
        }

        return out;
    }

    /**
     * 整型转换成字节数组
     */
    public static byte[] intToByteArray(int value) {
        byte[] byteArray = new byte[4];
        byteArray[0] = (byte) (value & 0xFF);
        byteArray[1] = (byte) (value >> 8 & 0xFF);
        byteArray[2] = (byte) (value >> 16 & 0xFF);
        byteArray[3] = (byte) (value >> 24 & 0xFF);
        return byteArray;
    }

    /**
     * 将byte数据组转成ascii字符串
     */
    public static String getAsciiString(byte[] bytes) {
        String asciiStr = new String(bytes);
        return asciiStr;
    }

    /**
     * byte数组转int类型的对象
     */
    public static int Byte2Int(byte[] bytes) {
        return (bytes[0] & 0xff) << 24
                | (bytes[1] & 0xff) << 16
                | (bytes[2] & 0xff) << 8
                | (bytes[3] & 0xff);
    }

    /**
     * 十六进制字符转换成整型
     */
    private static int hexToBin(char ch) {
        if ('0' <= ch && ch <= '9') return ch - '0';
        if ('A' <= ch && ch <= 'F') return ch - 'A' + 10;
        if ('a' <= ch && ch <= 'f') return ch - 'a' + 10;
        return -1;
    }

    /**
     * 字符转换成字节数组
     */
    public static byte[] charToByte(char c) {
        byte[] b = new byte[2];
        b[0] = (byte) ((c & 0xFF00) >> 8);
        b[1] = (byte) (c & 0xFF);
        return b;
    }

    /**
     * 将16进制单精度浮点型转换为10进制浮点型
     */
    public static float parseHex2Float(String hexStr) {
        BigInteger bigInteger = new BigInteger(hexStr, 16);
        return Float.intBitsToFloat(bigInteger.intValue());
    }

    /**
     * 十六进制字符串转换成字节数组
     */
    public static byte[] hexString2Bytes (String hexstring) {
        byte[] destByte = new byte[hexstring.length()/2];
        int j=0;
        for(int i=0;i<destByte.length;i++) {
            byte high = (byte) (Character.digit(hexstring.charAt(j), 16) & 0xff);
            byte low = (byte) (Character.digit(hexstring.charAt(j + 1), 16) & 0xff);
            destByte[i] = (byte) (high << 4 | low);
            j += 2;
        }
        return destByte;
    }

    /**
     * 十六进制字符串转换成字符串数组
     */
    public static String[] hexString2Arr (String hexstring) {
        final int len = hexstring.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("hexstring needs to be even-length: " + hexstring);
        }
        String[] destStr = new String[len/2];
        int j=0;
        for(int i=0;i<destStr.length;i++) {
            String high = String.valueOf(hexstring.charAt(j));
            String low = String.valueOf(hexstring.charAt(j + 1));
            destStr[i] = high + low;
            j += 2;
        }
        return destStr;
    }

    /**
     * 字符串过滤
     */
    public static String StringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字、中文
        // String regEx="[^a-zA-Z0-9]";
        // 清除掉[]中所有特殊字符
        String regEx = "[`~☆★!@#$%^&》·.<>/?~！@#￥%……（）——+【】‘；：”“’。，、]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String rep=m.replaceAll("").trim().replace(" ", "").replace("\\", "");
        Pattern p1 = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m1 = p1.matcher(rep);
        String repl = m1.replaceAll("");
        return repl;
    }

}
